package com.gin.kotlin.gf2gamecommunity.composable

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.paging.compose.LazyPagingItems
import com.gin.kotlin.enums.CommentSort
import com.gin.kotlin.gf2gamecommunity.app.DefaultCommentSort
import com.gin.kotlin.gf2gamecommunity.app.TopicImageShow
import com.gin.kotlin.gf2gamecommunity.base.composable.MyImage
import com.gin.kotlin.gf2gamecommunity.base.util.SIMPLE_DATE_TIME_FORMATTER
import com.gin.kotlin.gf2gamecommunity.routes.CommentListRoute
import com.gin.kotlin.response.topic.TopicInfo
import com.gin.kotlin.response.topic.ToppedTopic
import java.time.ZoneId

/**
 * 显示主题卡片的 LazyColumn
 * @param lazyPagingItems 数据
 * @param onNavigateToCommentList 跳转到主题详情
 * @param showAvatar 是否显示作者头像
 * @param modifier Modifier
 * @param state LazyListState
 */
@Composable
fun TopicLazyColumn(
    lazyPagingItems: LazyPagingItems<TopicInfo>,
    onNavigateToCommentList: (route: CommentListRoute) -> Unit,
    showAvatar: Boolean = true,
    state: LazyListState = rememberLazyListState(),
    toppedTopics: List<ToppedTopic>? = null,
    modifier: Modifier = Modifier,
) {
    val toppedCount = toppedTopics?.size ?: 0

    DefaultCommentSort { sort, _ ->
        LazyColumn(modifier = modifier, verticalArrangement = Arrangement.spacedBy(2.dp), contentPadding = PaddingValues(4.dp), state = state) {
            items(lazyPagingItems.itemCount + toppedCount, key = { it }) { index ->
                if (index < toppedCount) {
                    // 置顶帖
                    toppedTopics?.get(index)?.apply {
                        ToppedTopicItem(item = this,
                            index = index,
                            sort = sort,
                            onNavigateToCommentList = { r -> onNavigateToCommentList(r) }
                        )
                    }
                } else {
                    // 常规贴
                    lazyPagingItems[index - toppedCount]?.apply {
                        TopicItem(item = this,
                            index = index - toppedCount,
                            showAvatar = showAvatar,
                            sort = sort,
                            onNavigateToCommentList = { r -> onNavigateToCommentList(r) }
                        )
                    }
                }
            }
        }
    }
}


@Composable
fun TopicItem(item: TopicInfo, index: Int, onNavigateToCommentList: (route: CommentListRoute) -> Unit, showAvatar: Boolean = true, sort: CommentSort) {
    // 用户名+等级
    val username = remember(item) { derivedStateOf { "${item.userNickName} lv.${item.userLevel}" } }
    // 右下角计数器
    val count = remember(item) { derivedStateOf { "回: ${item.commentNum}, 赞: ${item.likeNum}" } }
    //  正文摘要
    val contentSummary = remember(item) {
        derivedStateOf {
            val limit = 20
            if (item.content.isEmpty()) {
                null
            } else if (item.content.length < limit) {
                item.content
            } else {
                item.content.substring(0, limit) + "..."
            }
        }
    }
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable {
                onNavigateToCommentList(CommentListRoute(topicId = item.topicId, temporaryTitle = item.title, sort = sort))
            },
        border = BorderStroke(2.dp, CardDefaults.cardColors().disabledContentColor),
    ) {
        Column(modifier = Modifier.padding(4.dp)) {
            //  用户信息：头像、用户名、等级
            if (showAvatar && item.userAvatar.isNotEmpty()) {
                Row {
                    UserAvatar(item.userAvatar, Modifier
                        .clip(CircleShape)
                        .size(48.dp)
                    )
                    Text(username.value)
                }
            }
            // 标题
            Text(item.title, fontWeight = FontWeight.Bold, fontSize = 20.sp)
            //  正文摘要
            contentSummary.value?.apply {
                Text(this, modifier = Modifier.graphicsLayer { alpha = 0.7f })
            }

            //  正文包含图片
            TopicImageShow { s, _ ->
                if (!item.picList.isNullOrEmpty() && s.show(LocalContext.current)) {
                    Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                        item.picList!!.forEach { url -> MyImage(model = url, modifier = Modifier.size(100.dp)) }
                    }
                }
            }
            // 主题信息：发帖时间、回复数、赞数
            Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
                Text(item.createTime.substring(2, item.createTime.length - 3), modifier = Modifier.align(Alignment.CenterVertically))
                if (item.userAvatar.isNotEmpty()) {
                    Text(count.value, modifier = Modifier.align(Alignment.CenterVertically))
                }
            }
        }

    }
}

@Composable
private fun ToppedTopicItem(item: ToppedTopic, index: Int, sort: CommentSort, onNavigateToCommentList: (route: CommentListRoute) -> Unit, modifier: Modifier = Modifier) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable {
                onNavigateToCommentList(CommentListRoute(topicId = item.topicId, temporaryTitle = item.title, sort = sort))
            },
        border = BorderStroke(2.dp, CardDefaults.cardColors().disabledContentColor),
    ) {
        Row(modifier = Modifier.padding(4.dp), verticalAlignment = Alignment.CenterVertically) {
            // 类型
            SuggestionChip(onClick = { }, label = { Text(item.type) })
            Column {
                // 标题
                Text(item.title, fontWeight = FontWeight.Bold, fontSize = 22.sp, maxLines = 2)
                // 时间
                Text(item.createTime.withZoneSameInstant(ZoneId.systemDefault()).format(SIMPLE_DATE_TIME_FORMATTER), modifier = Modifier.graphicsLayer { alpha = 0.7f })
            }
        }
    }
}